package com.mac.macjetpackdemo.util

import com.google.gson.JsonParseException
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.net.UnknownHostException

class NetUtil {

    suspend fun <T> net(
        block: () -> Deferred<T>,
        success: (result: T) -> Unit,
        failed: (Int, String?) -> Unit
    ) {
        withContext(Dispatchers.IO) {
            try {
                val deferred = block()
                success(deferred.await())
            } catch (e: Exception) {
                when (e) {
                    is HttpException -> {
                        failed(e.code(), e.message())
                    }
                    is JsonParseException -> {
                        failed(11, e.message)
                    }
                    is UnknownHostException -> {
                        failed(12, "网络异常")
                    }
                }
            }
        }
    }
}